﻿using Microsoft.AspNetCore.Http;
using System.Text;

namespace Core.Configuration.Helper
{
    public class WebHelper
    {
        public static string GetIP(HttpContext httpContext)
        {
            string ip = string.Empty;
            if (httpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
            {
                ip = httpContext.Request.Headers["X-Forwarded-For"];
            }
            if (string.IsNullOrEmpty(ip))
            {
                ip = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            return ip;
        }

        
        public static string GetRequestUri(HttpRequest request)
        {
            return new StringBuilder()
             .Append(request.Scheme)
             .Append("://")
             .Append(request.Host)
             .Append(request.PathBase)
             .Append(request.Path)
             .Append(request.QueryString)
             .ToString();
        }

        /// <summary>
        /// 获取post请求的主体参数
        /// </summary>
        /// <returns></returns>

        public static string GetRequestBody(HttpRequest request)
        {
            var body = string.Empty;
            using (var stream = new StreamReader(request.Body))
            {
                body = stream.ReadToEndAsync().GetAwaiter().GetResult();
            }
            return body;
        }
        //public static async Task<string> GetRequestBody(HttpRequest request)
        //{
        //    var body = string.Empty;

        //    using (var stream = new StreamReader(request.Body))
        //    {
        //        body = await stream.ReadToEndAsync();
        //    }
        //    return body;
        //}
    }
}
